const http = require('http')
const path = require("path")
const fs = require('fs')
const util = require("util")
// formidable是nodejs中用来上传图片的模块
var formidable = require('formidable')
const pathPublic = path.resolve(__dirname, '../static/public/images').replace(/\\/g, '/')
const readStaticFile = require('./public/index')
http.createServer(async (req, res) => {
    const url = req.url
    let form = new formidable.IncomingForm();
    form.keepExtensions = true;
    form.uploadDir = pathPublic;
    const { data, mimeType } = await readStaticFile(path.join(__dirname, "/public", url))
    if (req.url === '/upload') {
        form.parse(req, function (err, fields, files) {
            let oldFilename = files.fileUpload.name;
            let name = pathPublic + '/' + new Date().getTime() + '.' + oldFilename.split('.')[1]
            fs.rename(files.fileUpload.path, name, (err, data) => {
                console.log(data);
            })
            res.writeHead(200, { 'content-type': 'text/plain' });
            res.end(util.inspect({ fields: fields, files: files }));
        });
    } else {

        res.writeHead(200, {
            "content-type": mimeType
        })
        res.write(data)
        res.end()
    }

}).listen(8081)